var table;
$(function(){
    table=$("#account").DataTable({
        "ajax": {
            url:"../../admin/account/Get",
            type:"POST",
            data:function(d){
                d.accountName=$("#search_account").val()
                d.username=$("#search_username").val()
                d.status=$("#search_type").val()
            },error:function(XMLHttpRequest,textStatus,errorThrown){
                console.log("载入数据出错");
            }
        },
        "scrollX": 1500,
        "bProcessing": true,
        "bServerSide": true,
        "bPaginate": true,
        "bAutoWidth": false,
        "bInfo": true,//页脚信息
        "bFilter": false,//禁用搜索
        "bSort":false,//禁用排序
        "aLengthMenu": [2,5,10],
        "sPaginationType":'full_numbers',
        "columns": [
            {"data":"id"},
            { "data": "accountName" },
            { "data": "username" },
            { "data": "phone" },
            { "data": "fax" },
            { "data": "status" },
            { "data": "rolename" },
            { "data": "postTime" },
            { "data": "id" },
        ],
        "aoColumnDefs": [ {
            "aTargets": [ 5 ],
            "mRender": function ( data, type, full ) {
                switch (data){
                    case 1:return "作废";break;
                    case 2:return "锁定";break;
                    case 3:return "启用";break;
                    default :return "";break;
                }
            }
        },
            {
                "aTargets": [ 6 ],
                "mRender": function ( data, type, full ) {
                    if(data!='null'){
                        return $("#rolename").find("option[value='"+data+"']").text();
                    }
                    return "";
                }
            },
            {
                "aTargets": [ 8 ],
                "mRender": function ( data, type, full ) {
                    return '<a style="margin-left:12px" onclick="editAccount(\''+full.id+'\',\''+full.accountName+'\',\''+full.username+'\'' +
                        ',\''+full.phone+'\',\''+full.fax+'\',\''+full.rolename+'\',\''+full.status+'\')">修改</a>' +
                        '<a style="margin-left:12px" onclick="delAccount(\''+full.id+'\')">删除</a>' +
                        '<a style="margin-left:12px" onclick="unlockAccount(\''+full.id+'\')">解锁</a>' +
                        '<a style="margin-left:12px" onclick="resetPassword(\''+full.id+'\')">重设密码</a>';
                }
            }
        ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex) {
            $("td:first", nRow).html(iDisplayIndex + 1);
            return nRow;
        },
        "oLanguage": {
            "sProcessing": "处理中...",
            "sLengthMenu": "每页 _MENU_ 条",
            "sZeroRecords": "没有匹配结果",
            "sInfo": " _START_ 至 _END_ 项结果，共 _TOTAL_ 项",//显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项
            "sInfoEmpty": "",//显示第 0 至 0 项结果，共 0 项
            "sInfoFiltered": "",//(由 _MAX_ 项结果过滤)
            "sInfoPostFix": "",
            "sSearch": "搜索：",
            "sUrl": "",
            "sEmptyTable": "没有数据呀!",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            }
        },
    });
})

//偏好使用HTML
new SMValidator('#accountForm');

function searchAccount(){
    table.draw();
}

function addAccount(){
    $(".modal-title").text("用户添加")
    $("#id").val("")
    $("#accountName").val("")
    $("#username").val("")
    $("#phone").val("")
    $("#fax").val("");
    $("#add_status").find("option[value='"+3+"']").attr("selected",true);
    $("#rolename").find("option[value='"+0+"']").attr("selected",true);
    $("#accountModal").modal("show")
}

function account_sub(){
    if(SMValidator.validate('#accountForm')){
        $.ajax({
            url: "../../admin/account",
            type: "POST",
            dataType: "json",
            data: $("#accountForm").serialize(),
            beforeSend: function () {
            },
            success: function (data) {
                if(data){
                    var msg = ""
                    if($("#id").val()){
                        msg = "修改成功"
                    }else {
                        msg = "新增成功"
                    }
                    Lobibox.notify('success', {
                        msg: msg,
                        sound: false
                    });
                    $("#accountModal").modal("hide")
                    table.draw();
                }else {
                    console.log(data)
                }
            }, error: function () {
            }
        });
    }
}

function editAccount(id,accountName,username,phone,fax,rolename,status){
    Lobibox.confirm({
        msg: "确认要修改此用户?",
        title:"修改用户",
        iconClass: false,
        callback: function ($this, type, ev) {
            if(type==='yes'){
                $(".modal-title").text("用户修改")
                $("#id").val(id)
                $("#accountName").val(accountName)
                $("#username").val(username)
                if(phone!='null') {
                    $("#phone").val(phone)
                }else{
                    $("#phone").val("")
                }
                if(fax!='null') {
                    $("#fax").val(fax)
                }else{
                    $("#fax").val("")
                }
                if(status!='null') {
                    $("#add_status").find("option[value='"+status+"']").attr("selected",true);
                }else{
                    $("#add_status").find("option[value='"+0+"']").attr("selected",true);
                }

                if(rolename!='null') {
                    $("#rolename").find("option[value='"+rolename+"']").attr("selected",true);
                }else{
                    $("#rolename").find("option[value='"+0+"']").attr("selected",true);
                }
                $("#accountModal").modal("show")
            }
        }
    });
}

function delAccount(id){
    Lobibox.confirm({
        msg: "确认要删除此用户?",
        title:"删除用户",
        iconClass: false,
        callback: function ($this, type, ev) {
            if(type==='yes'){
                $.ajax({
                    url: "../../admin/account/"+id+"?_csrf="+$("input[name=_csrf]").val(),
                    type: "DELETE",
                    dataType: "json",
                    success: function (data) {
                        if(data){
                            table.draw();
                            Lobibox.notify('success', {
                                msg: '删除成功',
                                sound: false
                            });
                        }else {
                            Lobibox.notify('error', {
                                msg: '删除成功',
                                sound: false
                            });
                        }
                    }, error: function () {
                    }
                });
            }
        }
    });
}

function unlockAccount(id) {
    var SendData = {'id':id}
    SendData = JsonToSecurityString(SendData)
    Lobibox.confirm({
        msg: "确认是否需要解锁此用户?",
        title:"用户解锁",
        iconClass: false,
        callback: function ($this, type, ev) {
            if(type==='yes'){
                $.ajax({
                    type: "POST",
                    url: "../../admin/account/unlock",
                    data: SendData,
                    success: function(data) {
                        if(data){
                            table.draw();
                            Lobibox.notify('success', {
                                msg: '解锁成功',
                                sound: false
                            });
                        }else {
                            Lobibox.notify('error', {
                                msg: '解锁失败',
                                sound: false
                            });
                        }
                    }
                });
            }
        }
    });
}

function resetPassword(id) {
    var SendData = {'id':id}
    SendData = JsonToSecurityString(SendData)
    Lobibox.confirm({
        msg: "确认是否需要重设此用户的密码?",
        title:"用户密码重设",
        iconClass: false,
        callback: function ($this, type, ev) {
            if(type==='yes'){
                $.ajax({
                    type: "POST",
                    url: "../../admin/account/reset",
                    data: SendData,
                    success: function(data) {
                        if(data){
                            table.draw();
                            Lobibox.notify('success', {
                                msg: '重设成功',
                                sound: false
                            });
                        }else {
                            Lobibox.notify('error', {
                                msg: '重设失败',
                                sound: false
                            });
                        }
                    }
                });
            }
        }
    });
}

/**
 * @return {string}
 */
function JsonToSecurityString(SendData) {
    var eachData = {};
    eachData["_csrf"]=$("input[name=_csrf]").val();
    for(var i in SendData){
        eachData[i]=SendData[i];
    }
    var sendStr = "";
    for(var key in eachData){
        if (key=="_csrf"){
            sendStr += key + '=' + eachData[key];
        }else{
            sendStr += '&' + key + '=' + eachData[key];
        }
    }
    return sendStr;
}